/*

This file calculates the tex variables and table 1 for the Alpha paper.

*/
global writeout 0 // change to 1 for writing out, 0 to not
/* global quietly quietly // comment out for noisy */

$quietly { // top top quietly
clear
set more off
set seed 1337
set sortseed 1337

capture cd "~/Desktop/RESTAT_CODE"

global dir_root = "."
global dir_code = "${dir_root}/code"
global dir_data = "${dir_root}/data"
global dir_output "${dir_root}/output"


capture program drop countytable
program countytable, eclass
  version 13
  syntax varlist [if] [in], [STATistic(string) *]

  if "`statistic'" == "" local statistic "mean"
  local cname_slc "Salt Lake County"
  local cname_uc "Utah County"
  local cname_dc "Davis County"
  local cname_sc "Summit County"
  preserve
    if `"`if'`in'"' != `""' keep `if' `in'
    tempname mu_slc mu_uc mu_dc mu_sc
    foreach var of local varlist {
        foreach abbrv in slc uc dc sc {
          quietly sum `var' if COUNTY == "`cname_`abbrv''", `options'
          mat `mu_`abbrv'' = nullmat(`mu_`abbrv''), r(`statistic')
        }
    }
    foreach mat in mu_slc mu_uc mu_dc mu_sc {
        mat coln ``mat'' = `varlist'
    }
    tempname b V
    mat `b' = `mu_slc'*0
    mat `V' = `b''*`b'
    eret post `b' `V'
    eret local cmd "countytable"
    foreach mat in mu_slc mu_uc mu_dc mu_sc {
        eret mat `mat' = ``mat''
    }
  restore
end


*------------------------------------------------------------------------------*
*
*                      Load Dataset for House Level statistics
*
*------------------------------------------------------------------------------*

do "${dir_code}/1.0_load_data.do"

  global stat_vars population_per_county population_per_household mean_county_median_age ///
                   perc_hispanic_by_county mean_county_rate_5_7 county_deaths_5_7 households_sampled in_sample_households ///
                   cia_households pcr_households in_sample_individuals cia_individuals pcr_individuals ///
                   county_median_age sample_perc_hispanic sample_perc_female sample_perc_concern ///
                   pcr_county_mean cia_county_mean

    // This is a sanity check, standard deviations should all be zero
    eststo clear
    eststo: countytable $stat_vars, statistic(sd)
    esttab, nomtitle nonumbers noobs varwidth(30) ///
            cells("mu_slc(fmt(a3)) mu_uc(fmt(a3)) mu_dc(fmt(a3)) mu_sc(fmt(a3))")

    // This is the real output
    eststo clear
    eststo: countytable $stat_vars
    noisily esttab, nomtitle nonumbers noobs varwidth(30) ///
            cells("mu_slc(fmt(%9.3gc)) mu_uc(fmt(%9.3gc)) mu_dc(fmt(%9.3gc)) mu_sc(fmt(%9.3gc))")
    noisily esttab, nomtitle nonumbers noobs varwidth(30) booktabs type label ///
            cells("mu_slc(fmt(%9.3gc)) mu_uc(fmt(%9.3gc)) mu_dc(fmt(%9.3gc)) mu_sc(fmt(%9.3gc))")


*------------------------------------------------------------------------------*
*
* ████████╗███████╗██╗  ██╗    ██╗   ██╗ █████╗ ██████╗ ███████╗
* ╚══██╔══╝██╔════╝╚██╗██╔╝    ██║   ██║██╔══██╗██╔══██╗██╔════╝
*    ██║   █████╗   ╚███╔╝     ██║   ██║███████║██████╔╝███████╗
*    ██║   ██╔══╝   ██╔██╗     ╚██╗ ██╔╝██╔══██║██╔══██╗╚════██║
*    ██║   ███████╗██╔╝ ██╗     ╚████╔╝ ██║  ██║██║  ██║███████║
*    ╚═╝   ╚══════╝╚═╝  ╚═╝      ╚═══╝  ╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝
*
*                      Variables for paper text
*
*------------------------------------------------------------------------------*

* Individual level

*door knockers in practice
  count if (door_was_knocked == 1) & (any_test == 1)
  scalar individual_took_test_phase1 = r(N)
  noisily display "{txt}Number of individuals taking test Phase 1: {res}" %8.0gc `=individual_took_test_phase1'

* Letters only
  count if ((inlist(phase1_design, 2, 6) | (phase2 == 1)) & (door_was_knocked == 0)) & (any_test == 1)
  scalar individual_took_test_phase2 = r(N)
  noisily display "{txt}Number of individuals taking test Phase 2: {res}" %8.0gc `=individual_took_test_phase2'

* PCR numbers
  count if cia_individual == 1
  scalar individual_took_pcr = r(N)
  noisily display "{txt}Number of individuals taking PCR: {res}" %8.0gc `=individual_took_pcr'

* cia numbers
  count if pcr_individual == 1
  scalar individual_took_cia = r(N)
  noisily display "{txt}Number of individuals taking CIA: {res}" %8.0gc `=individual_took_cia'




* Household level
preserve // duplicates drop house_id, force
  capture drop sampled_house in_sample_house
  bysort house_id: egen sampled_house = max(sampled_individual)
  bysort house_id: egen in_sample_house = max(in_sample_individual)

  duplicates drop house_id, force

  tab door_was_knocked HH_visited, mi
  tab house_took_Survey HH_answer, mi

  tab phase1_design HH_visited, mi
  tab phase1_design door_was_knocked, mi
  tab phase1_design HH_complete_any, mi
  tab phase1_design house_took_Survey, mi


  *total sample size
    count if viable_tractgroup == 1
    scalar total_addresses = r(N)
    noisily display "{txt}% Total addresses available: {res}" %8.0gc `=total_addresses'

  *total sample size
    count if (sampled_house==1)
    scalar total_houses_sampled = r(N)
    noisily display "{txt}% Total houses contacted: {res}" %8.0gc `=total_houses_sampled'

  *door knockers in theory
    count if (sampled_house==1) & inlist(phase1_design, 1, 5)
    scalar door_sample = r(N)
    noisily display "{txt}Number planned knock houses: {res}" %8.0gc `=door_sample'

  *door knockers in practice
    count if (sampled_house==1) & (door_was_knocked == 1)
    scalar door_knocked_houses = r(N)
    noisily display "{txt}Number known houses knocked: {res}" %8.0gc `=door_knocked_houses'

  * Letters only Phase 1
    count if (sampled_house==1) & inlist(phase1_design, 2, 6) & (door_was_knocked == 0)
    scalar phase1_noknock = r(N)
    noisily display "{txt}Number Phase1 no-knock: {res}" %8.0gc `=phase1_noknock'

  * Letters only Phase 2
    count if (sampled_house==1) & !inlist(phase1_design, 1, 2, 5, 6) & (phase2 == 1) & (door_was_knocked == 0)
    scalar phase2_noknock = r(N)
    noisily display "{txt}Number Phase2 only: {res}" %8.0gc `=phase2_noknock'

  * Letters only
    count if (sampled_house==1) & (inlist(phase1_design, 2, 6) | (phase2 == 1)) & (door_was_knocked == 0)
    scalar letter_only_total = r(N)
    noisily display "{txt}Total houses letter only: {res}" %8.0gc `=letter_only_total'


  **************** Survey/PCR results at house level ********************************************

  foreach vartype in Survey CIA PCR AnyTest {
    *total sample size
      count if (house_took_`vartype' == 1) & (in_sample_house==1)
      scalar total_houses_sampled_`vartype' = r(N)
      noisily display "{txt}Total houses contacted AND took `vartype': {res}" %8.0gc `=total_houses_sampled_`vartype''

    *door knockers in practice
      count if (house_took_`vartype' == 1) & (door_was_knocked == 1) & (in_sample_house==1)
      scalar door_knocked_houses_`vartype' = r(N)
      noisily display "{txt}Number known houses knocked AND took `vartype': {res}" %8.0gc `=door_knocked_houses_`vartype''

    * Letters only Phase 1
      count if (house_took_`vartype' == 1) & (inlist(phase1_design, 1, 2, 5, 6) & (door_was_knocked == 0)) & (in_sample_house==1)
      scalar phase1_noknock_`vartype' = r(N)
      noisily display "{txt}Number Phase1 no-knock AND took `vartype': {res}" %8.0gc `=phase1_noknock_`vartype''

    * Letters only Phase 2
      count if (house_took_`vartype' == 1) & ((!inlist(phase1_design, 1, 2, 5, 6) & phase2 == 1) & (door_was_knocked == 0)) & (in_sample_house==1)
      scalar phase2_noknock_`vartype' = r(N)
      noisily display "{txt}Number Phase2 only AND took `vartype': {res}" %8.0gc `=phase2_noknock_`vartype''

    * Letters only
      count if (house_took_`vartype' == 1) & ((inlist(phase1_design, 1, 2, 5, 6) | (phase2 == 1)) & (door_was_knocked == 0)) & (in_sample_house==1)
      scalar letter_only_total_`vartype' = r(N)
      noisily display "{txt}Total houses letter only AND took `vartype': {res}" %8.0gc `=letter_only_total_`vartype''
  }
restore // duplicates drop house_id, force

    /* Copy the output below into your tex file for updated variables used in the paper. */
    noisily display "% Variables to be used below, generated from ./code/3.0_table_1.do"
    noisily display "    % Total Samples"
    noisily display "    \newcommand\varTotalAddresses{" %-10.0gc `=total_addresses' "}"
    noisily display "    \newcommand\varTotalHouses{" %-8.0gc `=total_houses_sampled' "}"
    noisily display "    \newcommand\varTotalHousesKnockedSample{" %-8.0gc `=door_sample' "}"
    noisily display "    \newcommand\varTotalHousesKnocked{" %-8.0gc `=door_knocked_houses' "}"
    noisily display "    \newcommand\varTotalHousesPhaseOneNoKnock{" %-8.0gc `=phase1_noknock' "}"
    noisily display "    \newcommand\varTotalHousesPhaseTwoNoKnock{" %-8.0gc `=phase2_noknock' "}"
    noisily display "    \newcommand\varTotalHousesLetters{" %-8.0gc `=letter_only_total' "}"

  foreach vartype in Survey CIA PCR AnyTest {
    noisily display "    % Total that took `vartype'"
    noisily display "    \newcommand\varTotalHouses`vartype'{" %-8.0gc `=total_houses_sampled_`vartype'' "}"
    noisily display "    \newcommand\varTotalHousesKnocked`vartype'{" %-8.0gc `=door_knocked_houses_`vartype'' "}"
    noisily display "    \newcommand\varTotalHousesPhaseOneNoKnock`vartype'{" %-8.0gc `=phase1_noknock_`vartype'' "}"
    noisily display "    \newcommand\varTotalHousesPhaseTwoNoKnock`vartype'{" %-8.0gc `=phase2_noknock_`vartype'' "}"
    noisily display "    \newcommand\varTotalHousesLetters`vartype'{" %-8.0gc `=letter_only_total_`vartype'' "}"
    noisily display "    % Percent that took `vartype'"
    noisily display "    \newcommand\varPercentHouses`vartype'{" %-4.1fc `=total_houses_sampled_`vartype'/total_houses_sampled*100' "}"
    noisily display "    \newcommand\varPercentHousesKnocked`vartype'{" %-4.1fc `=door_knocked_houses_`vartype'/door_knocked_houses*100' "}"
    noisily display "    \newcommand\varPercentHousesPhaseOneNoKnock`vartype'{" %-4.1fc `=phase1_noknock_`vartype'/phase1_noknock*100' "}"
    noisily display "    \newcommand\varPercentHousesPhaseTwoNoKnock`vartype'{" %-4.1fc `=phase2_noknock_`vartype'/phase2_noknock*100' "}"
    noisily display "    \newcommand\varPercentHousesLetters`vartype'{" %-4.1fc `=letter_only_total_`vartype'/letter_only_total*100' "}"
  }

  noisily display "    % Individual Stats"
  noisily display "    \newcommand\varIndividualsPerHousePhaseOneAnyTest{" %-4.1fc `=individual_took_test_phase1/door_knocked_houses_AnyTest' "}"
  noisily display "    \newcommand\varIndividualsPerHousePhaseTwoAnyTest{" %-4.1fc `=individual_took_test_phase2/letter_only_total_AnyTest' "}"
  noisily display "    \newcommand\varIndividualsTakingPCR{" %-8.0gc `=individual_took_pcr' "}"
  noisily display "    \newcommand\varIndividualsTakingCIA{" %-8.0gc `=individual_took_cia' "}"


} // end top top quietly
